<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-logo">
        <h1>本地会议助手</h1>
        <p>请登录您的账户</p>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="rules" 
        label-width="80px" 
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <div class="login-actions">
            <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            <el-button type="text" @click="handleForgotPassword">忘记密码？</el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            style="width: 100%" 
            @click="handleLogin"
            :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

export default {
  name: 'LoginPage',
  emits: ['login-success'], // 声明事件
  setup(props, { emit }) {
    // 表单数据
    const loginForm = reactive({
      username: '',
      password: '',
      rememberMe: false
    });
    
    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    };
    
    // 其他状态
    const loginFormRef = ref(null);
    const loading = ref(false);
    
    // 模拟用户数据（实际项目中应该从后端获取）
    const mockUsers = [
      { username: 'admin', password: '123456', role: 'admin' },
      { username: 'user1', password: '123456', role: 'user' },
      { username: 'test', password: 'test123!', role: 'user' } // 测试账号
    ];
    
    // 处理登录
    const handleLogin = async () => {
      try {
        // 表单验证
        await loginFormRef.value.validate();
        
        // 显示加载状态
        loading.value = true;
        
        // 模拟登录请求延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 验证用户名和密码
        const user = mockUsers.find(
          u => u.username === loginForm.username && u.password === loginForm.password
        );
        
        if (user) {
          // 存储用户信息到localStorage（实际项目中应该使用JWT等安全的方式）
          const userInfo = {
            username: user.username,
            role: user.role,
            token: 'mock-jwt-token-' + Date.now() // 模拟token
          };
          
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          
          // 记住密码功能（实际项目中应加密存储）
          if (loginForm.rememberMe) {
            localStorage.setItem('rememberedUser', JSON.stringify({
              username: loginForm.username
            }));
          } else {
            localStorage.removeItem('rememberedUser');
          }
          
          ElMessage.success('登录成功');
          
          // 触发登录成功事件通知父组件
          emit('login-success', userInfo);
          
          // 跳转到会议助手页面
          window.location.reload(); // 简单地刷新页面来触发路由变化
        } else {
          ElMessage.error('用户名或密码错误');
        }
      } catch (error) {
        if (error === false) {
          // 表单验证失败，不做处理
        } else {
          ElMessage.error('登录失败，请稍后重试');
          console.error('Login error:', error);
        }
      } finally {
        loading.value = false;
      }
    };
    
    // 处理忘记密码
    const handleForgotPassword = () => {
      ElMessage.info('忘记密码功能正在开发中');
    };
    
    // 页面加载时，检查是否有记住的用户
    const rememberedUser = localStorage.getItem('rememberedUser');
    if (rememberedUser) {
      try {
        const user = JSON.parse(rememberedUser);
        loginForm.username = user.username;
        loginForm.rememberMe = true;
      } catch (e) {
        console.error('Failed to parse remembered user:', e);
      }
    }
    
    return {
      loginForm,
      rules,
      loginFormRef,
      loading,
      handleLogin,
      handleForgotPassword
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: cover;
  background-position: center;
}

.login-form-wrapper {
  background: white;
  border-radius: 12px;
  padding: 40px;
  width: 400px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.login-form-wrapper:hover {
  transform: translateY(-5px);
}

.login-logo {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo h1 {
  color: #667eea;
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 600;
}

.login-logo p {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.login-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 输入框聚焦效果 */
:deep(.el-input__wrapper:focus-within) {
  border-color: #667eea !important;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2) !important;
}

/* 按钮样式优化 */
:deep(.el-button--primary) {
  background-color: #667eea;
  border-color: #667eea;
}

:deep(.el-button--primary:hover) {
  background-color: #5a67d8;
  border-color: #5a67d8;
}
</style>